import React, { useEffect, useState } from 'react';
import AppOrchestration from '../app-orchestration';
import { useLocation, useNavigate } from 'react-router-dom';
import appService from '@/api/services/appService';
import { Button, Input, message } from 'antd';
import useModal from '@/hooks/use-modal/useModal';
import Modals from '@/components/modals/Modals';
import { ReviewAppRes } from '@/common/types';
import { formatData } from '@/utils/time';
import { useParams, useRouter } from '@/router/hooks';
import AppWorkFlow from '@/pages/app/detail/index';

const ViewAppOrchestration = () => {
  const location = useLocation();
  const navigate = useNavigate();
  // const [appId, setAppId] = useState('');
  const modal = useModal('review', 'dismiss');
  const [dismiss, setDismiss] = useState('');
  const [tipsValue, setTipsValue] = useState<ReviewAppRes>();
  const router = useRouter();

  const {
    appId = '',
    appType = '',
    key = '',
  } = useParams() as {
    appId: string;
    appType: string;
    key: string;
  };

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const paramsObject = Object.fromEntries(searchParams.entries());
    // setAppId(paramsObject.appId);
  }, []);

  const goBack = () => {
    router.push('/worklayouts/appReviewCenter/app-review?key=' + key);
  };

  /**
   * @description: 审核通过
   * @return {*}
   */
  const handlePassed = () => {
    appService
      .reviewApp(appId, {
        review_result: 'pass',
        review_description: '',
      })
      .then((res) => {
        if (res.reviewer) {
          setTipsValue(res);
          modal.review.open();
          return;
        }
        message.success('审核通过');
        goBack();
      });
  };

  /**
   * @description: 点击确定弹窗
   * @return {*}
   */
  const handleModalOk = () => {
    if (dismiss.trim().length === 0) {
      message.error('请填写驳回原因');
      return;
    }
    modal.dismiss.startLoading();
    appService
      .reviewApp(appId as string, {
        review_result: 'reject',
        review_description: dismiss,
      })
      .then((res) => {
        if (res.reviewer) {
          setTipsValue(res);
          modal.review.open();
          return;
        }
        message.warning('审批已驳回!');
        setDismiss('');
        modal.dismiss.close();
        goBack();
      })
      .finally(() => {
        modal.dismiss.stopLoading();
      });
  };

  /**
   * @description: 开启弹窗
   * @return {*}
   */
  const handleModalOpen = () => {
    // setDefaultDismiss(value);
    modal.dismiss.open();
  };

  return (
    <div className="h-full w-full">
      {appType === 'workflow' || appType === 'plugin' ? (
        <div className="h-full w-full">
          <AppWorkFlow />
          {key !== '2' && (
            <div className="absolute right-0 top-3">
              <div className="mr-8 flex items-center gap-2">
                <Button type="text" style={{ color: '#1AA839' }} onClick={handlePassed}>
                  通过
                </Button>
                <Button type="text" style={{ color: '#FF2604' }} onClick={handleModalOpen}>
                  驳回
                </Button>
              </div>
            </div>
          )}
        </div>
      ) : (
        <AppOrchestration
          isPreview={true}
          onApprove={handlePassed}
          onReject={handleModalOpen}
          onReturn={goBack}
          previewBtn={key === '2'}
        />
      )}

      <Modals
        title={<div className="text-nowrap text-sm text-[#474C5F]">驳回原因</div>}
        open={modal.dismiss.isOpen}
        onOk={handleModalOk}
        onCancel={() => {
          modal.dismiss.close();
          setDismiss('');
        }}
        confirmLoading={modal.dismiss.isLoading}
      >
        <Input.TextArea
          placeholder="请输入驳回原因"
          autoSize={{ minRows: 10, maxRows: 10 }}
          classNames={{
            textarea: '!border-0 !bg-[#F3F4F9]',
          }}
          value={dismiss}
          onChange={(e) => setDismiss(e.target.value)}
        />
      </Modals>

      <Modals
        title={`该应用已${tipsValue?.review_description ? '驳回' : '通过'}`}
        open={modal.review.isOpen}
        footerCancelHidden
        okText="知道了"
        onOk={() => {
          modal.review.close();
          modal.dismiss.close();
        }}
        zIndex={999999}
      >
        <div>审批人:{tipsValue?.reviewer}</div>
        <div>审批时间:{formatData(tipsValue?.update_time ? tipsValue?.update_time : '')}</div>
        {tipsValue?.review_description && <div>驳回原因:{tipsValue?.review_description}</div>}
      </Modals>
    </div>
  );
};

export default ViewAppOrchestration;
